<template>
<div>
  <div style="color: #00faff;margin-bottom: 5px" v-for="item in fileList" :key="item"  class="downFile" @click="downloadFileFromBackend(item)">{{item}}</div>
</div>
</template>

<script>
import { Loading } from 'element-ui';
export default {
  name: 'downFile',
  props: {
    file: {
      type: String,
      default:''
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  mounted() {
    console.log(this.file)
    this.fileList = this.file.split(',')
    console.log(this.fileList )
  },
  methods: {
    async downloadFileFromBackend(fileUrl) {
      console.log('到下载了---------------------------')
      // this.$loading('正在下载请稍候......')
      const loading = Loading.service({
        target: '.your-loading-container', // 可选，指定加载遮罩作用的DOM元素，默认全屏
        text: '正在下载请稍候...', // 自定义加载文案
        spinner: 'el-icon-loading', // 加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', // 背景颜色
      });
      try {
        // 直接使用后端返回的URL进行下载，过程与之前提到的方法相同
        const response = await fetch(fileUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = this.extractFileNameFromUrl(fileUrl);
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载文件时发生错误:', error);
      } finally {
        loading.close();      }
    },

    // 文件名提取函数
    extractFileNameFromUrl(url) {
      const urlParts = url.split('/');
      return decodeURIComponent(urlParts[urlParts.length - 1]);
    }
  }
}
</script>

<style scoped>

</style>
